package com.example.base;

import com.example.entity.Customer;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.formats.json.JsonDeserializationSchema;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Author wangJinLong
 * Date 2025/8/21 08:26
 **/
public class FlinkStreamKafka {
    public static void main(String[] args) throws Exception {
        jsonValue();
    }

    private static void jsonValue() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        KafkaSource<Customer> source = KafkaSource.<Customer>builder()
                .setBootstrapServers("106.54.174.109:19092")
                .setTopics("data-user")
                .setGroupId("my-group1")
                .setStartingOffsets(OffsetsInitializer.earliest())
                .setValueOnlyDeserializer(new JsonDeserializationSchema<>(Customer.class))
                .build();

        DataStreamSource<Customer> dataStreamSource =
                env.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");

        dataStreamSource.print();

        env.execute();
    }

    private static void simpleValue() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        KafkaSource<String> source = KafkaSource.<String>builder()
                .setBootstrapServers("106.54.174.109:19092")
                .setTopics("data-user")
                .setGroupId("my-group")
                .setStartingOffsets(OffsetsInitializer.earliest())
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .build();

        DataStreamSource<String> dataStreamSource =
                env.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");

        dataStreamSource.print();

        env.execute();
    }
}
